package com.smartao.base.employee;

import java.util.Set;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.encoding.PasswordEncoder;
import org.springframework.stereotype.Service;

import com.smartao.base.Constant;
import com.smartao.base.init.InitializeServiceOrder;
import com.smartao.base.role.Role;
import com.smartao.base.role.RoleService;
import com.smartao.core.init.AbstractDataInitializeService;

/**
 * 初始化管理员(admin)
 * @author Ricky
 */
@Service
public class EmployeeInitializeService extends AbstractDataInitializeService {

	private static final String ADMIN = "admin";
	private static final String ADMIN_NAME = "管理员";
	private static final String PASSWD = "admin@smartao";

	protected final int order = InitializeServiceOrder.INIT_ORDER_USER;

	@Autowired
	private PasswordEncoder passwordEncoder;
	@Autowired
	private EmployeeService employeeService;
	@Autowired
	private RoleService roleService;

	@Override
	public void initData() throws Exception {
		Employee user = (Employee) employeeService.findUserByAccount(ADMIN);
		Role admin = roleService.findByRoleKey(Constant.ROLE_ADMIN);
		//判断admin是否存在
		if (user == null) {
			logger.info("Admin user not found,will create one.");
			String password = passwordEncoder.encodePassword(PASSWD, null);
			user = new Employee();
			user.setAccount(ADMIN);
			user.setName(ADMIN_NAME);
			user.setPassword(password);
			user.addRole(admin);
			employeeService.save(user);
		} else {
			//List<Role> roles = roleService.findUserRoles(user);
			Set<Role> roles = user.getRoles();
			//判断user是否有admin角色
			if (roles == null) {
				user.addRole(admin);
				employeeService.save(user);
			}
		}
		
		for(int i=0; i<40; i++){
			Employee em = new Employee();
			em.setName("user" + i);
			em.setAccount("user" + i);
			em.setAccountStatus(AccountStatus.active);
			employeeService.save(em);
		}
	}

	@Override
	public int getOrder() {
		return order;
	}

}
